﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Linq;
using ServiceStack.Logging;
using g42.Dto;
using g42.Entities;
using g42.MapEntitiesDto;

namespace g42.Repos
{
  public class MandantRepository
  {
    ILog log;

    public MandantRepository()
    {
      log = LogManager.GetLogger(GetType());
    }

    public Mandant Get()
    {
      try
      {
        using (var session = db.sessionFactory.OpenSession())
        {
          using (session.BeginTransaction())
          {
            // Entity-Objekt lesen
            var MandantList = 
              (from md in session.Query<MandantEnt>()
               select md);
            // Einfach den ersten nehmen
            var Mandant = MandantList.First();
            // Entity-Objekt in DTO transformieren
            return Mandant.ToMandant();
          }
        }
      }
      catch (Exception E)
      {
        log.Error("Error MandantRepository.Get(): " + E.Message + System.Environment.NewLine + E.InnerException);
        return null;
      }
    }

    public Mandant Store(Mandant dto)
    {
      try
      {
        using (var session = db.sessionFactory.OpenSession())
        {
          using (var transaction = session.BeginTransaction())
          {
            MandantEnt ent = dto.ToMandantEnt();
            session.SaveOrUpdate(ent); // die Id kommt beim Speichern zurück
            transaction.Commit();
            dto.Id = ent.Id;
            return dto;
          }
        }
      }
      catch (Exception E)
      {
        log.Error("Error MandantRepository.Store(): " + E.Message + System.Environment.NewLine + E.InnerException);
        return null;
      }
    }

  }
}

